﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GeoUtils;

namespace GeoCoderParser
{
    class NaiveGeoEntityChainRanker : IGeoEntityChainRanker
    {
        public NaiveGeoEntityChainRanker()
        {


        }

        public void Initialize(string strConfigFileName)
        {


        }

        //Rank all geo-entity chain list
        public List<GeoEntityChain> RankGeoEntityChains(List<Token> tokenList, List<GeoEntityChain> geoItemChainList, ViewPort viewport)
        {
            List<GeoEntityChain> rstGeoEntityChainList = new List<GeoEntityChain>();

            //First, rank result as geo-entity chain size
            SortedDictionary<int, List<GeoEntityChain>> sdict = new SortedDictionary<int, List<GeoEntityChain>>();
            foreach (GeoEntityChain geoEntityChain in geoItemChainList)
            {
                int cnt = geoEntityChain.geoEntityList.Count;
                if (sdict.ContainsKey(cnt) == false)
                {
                    sdict.Add(cnt, new List<GeoEntityChain>());
                }
                sdict[cnt].Add(geoEntityChain);
            }

            //Second, for each geo-entity chain size, rank them by level
            foreach (KeyValuePair<int, List<GeoEntityChain>> pair in sdict.Reverse())
            {
                List<GeoEntityChain> rst = RankGeoEntityChainByLevel(pair.Value);
                rstGeoEntityChainList.AddRange(rst);
            }

            return rstGeoEntityChainList;
        }

        //Rank location chain by level
        private List<GeoEntityChain> RankGeoEntityChainByLevel(List<GeoEntityChain> geoItemChainList)
        {
            SortedDictionary<int, List<GeoEntityChain>> sdict = new SortedDictionary<int, List<GeoEntityChain>>();
            foreach (GeoEntityChain geoItemChain in geoItemChainList)
            {
                //Get the biggest level in a geo-items chain
                int iLevel = 1000;
                foreach (GeoEntity item in geoItemChain.geoEntityList)
                {
                    if (item.iLevel < iLevel)
                    {
                        iLevel = item.iLevel;
                    }
                }

                if (sdict.ContainsKey(iLevel) == false)
                {
                    sdict.Add(iLevel, new List<GeoEntityChain>());
                }
                sdict[iLevel].Add(geoItemChain);
            }

            List<GeoEntityChain> rst = new List<GeoEntityChain>();
            foreach (KeyValuePair<int, List<GeoEntityChain>> pair in sdict)
            {
                foreach (GeoEntityChain item in pair.Value)
                {
                    rst.Add(item);
                }
            }

            return rst;
        }
    }
}
